--------------------------------------------------------------------------------
-- \file     extract.lua
-- \brief    Converts defines to lua tables for peripheral emulation
-- \version  1
-- \date     2013-03-11 1:08PM
-- \author   ACV
--------------------------------------------------------------------------------
file_header = [[
--------------------------------------------------------------------------------
-- \file     %s.lua
-- \brief    Register class for nccas peripheral emulation.
-- \version  1
-- \date     %s
-- \author   %s
--------------------------------------------------------------------------------
%s_registers = {
]]
file_end = [[
}

--
--	End: %s.lua
--
]]

--------------------------------------------------------------------------------
-- \brief Local Begin / End functions
-- These are called at the begin and end of the program execution
--------------------------------------------------------------------------------
function LocalBegin(fn)
	local curr_file = fn
	local curr_date = os.date("%Y-%m-%d %X")
	local curr_user = os.getenv("USERNAME")
	local base_class = string.sub(curr_file,1,#curr_file-2)
	local out_file = base_class .. ".lua"

	io.output(out_file)
	io.write(string.format(file_header, base_class, curr_date, curr_user, base_class))
end
function LocalEnd(fn)
	local curr_file = fn
	local curr_date = os.date("%Y-%m-%d %X")
	local curr_user = os.getenv("USERNAME")
	local base_class = string.sub(curr_file,1,#curr_file-2)

	io.write(string.format(file_end, base_class))
	io.close()
end

--------------------------------------------------------------------------------
-- \brief Processing function
-- This function processes each file in the order specified on the command line
--------------------------------------------------------------------------------
function Process(fn)
	local pass_one = true
	for line in io.lines(fn) do
		local def_symbol,def_value = string.match(line,"^#define%s+([%w_]+)%s+(0x%x+)")
		if def_symbol then
			if (pass_one == true) then
				base = def_value
				pass_one = false
			else
				local reg_lo = def_symbol .. "_low"
				local reg_hi = def_symbol .. "_high"
				io.write(string.format("\t%-48s= 0x%08X,\n", reg_lo,base+def_value))
				io.write(string.format("\t%-48s= 0x%08X,\n", reg_hi,base+def_value+4))
			end
		end
	end
end

--------------------------------------------------------------------------------
-- \brief AWK like processing
-- Handles single or multiple files
--------------------------------------------------------------------------------
for v=1,#arg do
	LocalBegin(arg[v])
	Process(arg[v])
	LocalEnd(arg[v])
end

--
--	End: extract.lua
--
